
package tutorials;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author timon
 */
public class UpdateFrameComponents {
  
  // Create a visible label
  public JLabel lbl_Visible = new JLabel("Always Visible");
  
  // Create a label which we will insert into the frame on update
  public JLabel lbl_AddIn = new JLabel("Added In");
  
  // Button which updates the panel
  public JButton btn_Update = new JButton("Update");
  
  // The panels to hold our components
  JPanel labels = new JPanel();
  JPanel buttons = new JPanel();
  
  // JFrame for content display
  JFrame display = new JFrame();
  
  public UpdateFrameComponents() {

    // setup panels and add components
    labels.setLayout(new GridLayout(2,1));
    labels.add(lbl_Visible);

    buttons.setLayout(new FlowLayout());
    buttons.add(btn_Update);

    // Add the UpdateListener (see below) to btn_Update
    btn_Update.addActionListener(new UpdateListener());

    // Format the dispaly frame and add content.
    display.setLayout(new BorderLayout());
    display.add(buttons, BorderLayout.SOUTH);
    display.add(labels, BorderLayout.CENTER);

    display.setSize(200,200);
    display.setTitle("Frame Update Tutorial");
    display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    display.setLocationRelativeTo(null);
    display.setVisible(true);
  }
  
  /** 
   * This listener will trigger the update when btn_Update
   * is clicked
   */
  class UpdateListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

      // Verify that we haven't already updated.
      Component[] comps = labels.getComponents();
      boolean hasUpdated = false;

      // Loop through the components of the labels panel
      for (int i = 0 ; i < comps.length ; i++) {

        // If lbl_AddIn is found, set the hasUpdated flag = true
        if (comps[i].equals(lbl_AddIn)) {

          hasUpdated = true;
        }
      }

      // If we haven't updated, go ahead and add the new label
      // to the panel.
      if (!hasUpdated) {

        labels.add(lbl_AddIn);
      }

      // Update and refresh the labels panel on the UI
      labels.updateUI();
    }

  }
  
  /**
   * Run the tutorial
   * 
   * @param args 
   */
  public static void main(String[] args) {

    // Instantiate this class
    new UpdateFrameComponents();
  }
  
 
  
  
}
